import { defineStore } from 'pinia'
import { api } from '../api/client'

export interface MenuNode {
  id: string
  name: string
  path: string
  icon?: string
  children: MenuNode[]
}

// 将后端菜单路径规范化为 /admin 前缀（兼容旧路径）
const ADMIN_PREFIX_MAP: Record<string, string> = {
  '/dashboard': '/admin/dashboard',
  '/activities': '/admin/activities',
  '/events': '/admin/events',
  '/evaluations': '/admin/evaluations',
  '/reports': '/admin/reports',
}
const normalizeAdminPath = (p: string) => ADMIN_PREFIX_MAP[p] || p
const cloneAndNormalize = (nodes: MenuNode[]): MenuNode[] =>
  (nodes || []).map((n) => ({
    ...n,
    path: normalizeAdminPath(n.path),
    children: cloneAndNormalize(n.children || []),
  }))

export const useMenuStore = defineStore('menu', {
  state: () => ({
    tree: [] as MenuNode[],
    loading: false,
  }),
  getters: {
    // 供路由守卫使用的允许访问路径（已规范到 /admin 前缀）
    allowedPaths: (state) => {
      const set = new Set<string>()
      const walk = (nodes: MenuNode[]) => {
        for (const n of nodes || []) {
          if (n.path) set.add(normalizeAdminPath(n.path))
          if (n.children && n.children.length) walk(n.children)
        }
      }
      walk(state.tree || [])
      return Array.from(set)
    },
    // 计算首个可访问路径（已规范到 /admin 前缀）
    firstPath: (state) => {
      const first = (nodes: MenuNode[]): string | null => {
        for (const n of nodes || []) {
          if (n.children && n.children.length) {
            const fp = first(n.children)
            if (fp) return fp
          }
          if (n.path) return normalizeAdminPath(n.path)
        }
        return null
      }
      return first(state.tree) || null
    },
    // 优先返回以 /admin 开头的首个可访问路径
    firstAdminPath: (state) => {
      const firstAdmin = (nodes: MenuNode[]): string | null => {
        for (const n of nodes || []) {
          // 先看当前节点（优先当前，再递归子节点）
          if (n.path) {
            const p = normalizeAdminPath(n.path)
            if (p.startsWith('/admin')) return p
          }
          if (n.children && n.children.length) {
            const fp = firstAdmin(n.children)
            if (fp) return fp
          }
        }
        return null
      }
      return firstAdmin(state.tree) || null
    },
    // UI 使用：返回路径已规范化的菜单树
    uiTree: (state) => cloneAndNormalize(state.tree || []),
  },
  actions: {
    async loadTree() {
      this.loading = true
      try {
        const resp = await api.get('/menus/tree')
        this.tree = resp.data || []
      } finally {
        this.loading = false
      }
    },
    setTree(tree: MenuNode[]) {
      this.tree = tree
    },
  },
})